<div id="notify-message" class="alert alert-info hide">
</div>
<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container-fluid" style="padding-top: 0px;padding-bottom:0px; height: 39px">
			<a class="brand" href="/"><img src="/site_media/images/heading.png"></a>
			{% if profile %}
			<ul class="nav secondary-nav pull-right">
				<li class="dropdown">
					<a href="#" data-toggle="dropdown" class="dropdown-toggle">
					  <i class="icon-user icon-white"></i>&nbsp&nbsp<span class="username_of_{{ profile.id }}">{{ profile.name }}</span>
					</a>
					<ul class="dropdown-menu">
						<li><a id="update-profile-button" data-toggle="modal" href="#profile_update_modal"><i class="icon-pencil"></i>&nbsp&nbspUpdate Profile</a></li>
						<li><a href="/logout/"><i class="icon-ban-circle"></i>&nbsp&nbspLogout</a></li>
					</ul>
				</li>
			</ul>
			<div class="btn btn-danger pull-right badge" id="request_count" data-toggle="toggle"></div>
			{% endif %}
			{% if game %}
			<ul class="nav secondary-nav pull-right">
        <li class="dropdown">
          <a href="#" data-toggle="dropdown" class="dropdown-toggle">
            <i class="icon-cog icon-white"></i>&nbsp&nbspGame: {{ game.name }}
          </a>
          <ul class="dropdown-menu">
            <li><a id="forfeit-game-button"><i class="icon-remove"></i>&nbsp&nbspForfeit Game</a></li>
            <li><a id="see-stats-button" href="#"><i class="icon-list"></i>&nbsp&nbspSee Stats</a></li>
            <li><a id="invite-button" href="#"><i class="icon-share-alt"></i>&nbsp&nbspInvite</a></li>
          </ul>
        </li>
      </ul>
			{% endif %}
		</div>
	</div>
  <div id="friend-request-view" class="well pull-right hide" style="min-width:273px; max-height: 195px; overflow: auto;"></div>
</div>
<div id="profile_update_modal" class="modal hide fade" style="width: 468px;overflow:visible;">
	<div id="profile_update_modal_header" class="modal-header">
		<a id="profile_update_close" href="#" class="close" data-dismiss="modal"><i class="icon-remove"></i></a>
	  <h3>{% if profile.user.email %}<img src="/site_media/images/google.png"
          width="23.5" style="padding-top: 9px"/>&nbsp;&nbsp;&nbsp;{% endif %}Profile Settings</h3>
	</div>
	<div id="profile_update_modal_body" class="modal-body" style="height: 345px">
	  {% if profile.user.email %}
	   <p><strong>Google Account: </strong><span class="label">{{ profile.user.email }}</span></p>
	  {% else %}
	   <p><span class="label">Spargame.com account</span></p>
	  {% endif %}
		<strong>Nickname: </strong><input id="user_name" name="user_name" type="text"
		value="{{ profile.name }}"> <span id="name_status" class="label label-success">OK</span><br>
		<span style="margin-top: 25px"><strong>Avatar:</strong></span><br>
		{% include "avatar_selector.html" %}
	  <div><a id="show_image_upload"class="nounderline" href="#">Upload New Image</a></div>
	</div>
	<div id="image_upload_modal_body" class="modal-body hide" style="height: 345px">
	  {% include "image_upload.html" %}
	  <div><a id="hide_image_upload"class="nounderline" href="#">Choose Existing Avatar</a></div>
	</div>
	<div class="modal-footer">
		<button id="save_profile_changes" class="btn primary">Save</button>
	</div>
</div>
<div class="footer">
  <p>Spargame Copyright (c) {% now "Y" %}</p>
</div>
<div id="game_loading_modal" class="modal fade" style="width: 416px">
  <div class="modal-body">
    <div class="progress progress-info progress-striped active">
		  <div id="loading-bar" class="bar" style="width: 0%;"></div>
		</div>
  </div>
  <div class="modal-footer">
    Loading
  </div>
</div>
<script type="text/javascript">
  window.show_loading = false;

	$(document).ready(function() {
		$("body").fadeIn(1000);

		window.engineRef = null;
		window.onEngineReady = function (lsEngine) {
	    window.engineRef = lsEngine;
	    if (show_loading) {
		    $("#loading-bar").animate({width: "+=100%"}, function() {
		    	$('#game_loading_modal').fadeOut("fast", function() {
		        $(".modal-backdrop").fadeOut("fast");
		    	});
		    });
	    }
	  };

	  $('#profile_update_modal').on('hidden', function () {
		  $("#hide_image_upload").click();
		})

	  $("#show_image_upload").click(function(){
		  $("#profile_update_modal_body").hide("slide", { direction: "left" }, "fast", function(){
  		  $("#image_upload_modal_body").show("slide", { direction: "right" }, "fast");
  		$("#save_profile_changes").css("opacity", 0);
  		$("#save_profile_changes").attr("disabled", "disabled");
		  });
	  });

	  $("#hide_image_upload").click(function(){
	      $("#image_upload_modal_body").hide("slide", { direction: "right" }, "fast", function(){
  	      $("#profile_update_modal_body").show("slide", { direction: "left" }, "fast");
  	      $("#save_profile_changes").css("opacity", 1);
  	      $("#save_profile_changes").removeAttr("disabled");
	      });
	    });

		$("#save_profile_changes").click(function(data) {
			  if (!$("#save_profile_changes").hasClass("disabled")) {
			    var userName = $("#user_name").val();
			    $.post("/updateProfile/", {"user_name":userName, "user_avatar": userAvatar})
			    .success(function() {
			    	if(userName != window.playerMap[currentPlayer]){
			    	  sendProfileUpdate("name", window.playerMap[currentPlayer], userName);
			    	  updateUsernameFields(userName);
			    	}
			    	if(userAvatar != window.avatarMap[currentPlayer]){
			    	  $("#profile").attr("src", userAvatar);
			    	  sendProfileUpdate("avatar", window.avatarMap[currentPlayer], userAvatar);
			    	}
			     })
			    .error(function(error) { alert("Oops... Unable to save data. Please refresh page" + error); });
			    $('#profile_update_modal').modal('hide');
			  }
		});

		$("#user_name").keyup(function() {
			  $.post("/isPlayerNameUnique/", {"name":$("#user_name").val()})
        .success(function(data) {
        	if(data["unique"] == true){
        		$("#name_status").text("OK");
        		$("#name_status").removeClass("label-warning");
        		$("#name_status").addClass("label-success");
        		$("#save_profile_changes").removeClass("disabled");
        	}
        	else {
        		$("#name_status").text("Not available");
        		$("#name_status").removeClass("label-success");
            $("#name_status").addClass("label-warning");
            $("#save_profile_changes").addClass("disabled");
        	}
        })
        .error(function(error) {alert("Oops... Unable to save data. Please refresh page" + error);});
		});

		$("#user_name").keypress(function(event) {
         var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
         if (keycode == 13) {
             $('#save_profile_changes').click();
         }
     });

		function sendProfileUpdate(field, oldValue, newValue) {
			var mex = "PLAYER_PROFILE_UPDATES|{{ profile.id }}|" + field + "|" + oldValue + "|" +
			newValue + "|{{ profile.getActiveGameIds }}";
		  engineRef.sendMessage(mex, null, 5000);
    }

		function updateUsernameFields(newUserName) {
			jQuery(".username_of_{{ profile.id }}").each(function(){
				$( this ).text(newUserName);
			});
		}

		var onFriendRequestReceived = function (itemPos, updateInfo, itemName) {
       var playerName = updateInfo.getNewValue("player_name");
       var playerId = updateInfo.getNewValue("player_id");
       var playId = updateInfo.getNewValue("play_id");
       addFriendRequest(playerName, playerId, playId);
	  };

	  var onAcceptRequestReceived = function (itemPos, updateInfo, itemName) {
       var playerName = updateInfo.getNewValue("player_name");
       var playerId = updateInfo.getNewValue("player_id");
       var count = 0;
       if ($("#request_count").text().length > 0) {
         count = parseInt($("#request_count").text());
       }
       $("#request_count").text(++count);
       $("#request_count").show();
       var clone = $("#notify-message").clone();
       clone.addClass("request-accept");
       clone.html("<div><strong>" + playerName + "</strong> has accepted your friend request</div>");
       clone.appendTo("#friend-request-view");
       clone.fadeIn(500);
    };

	  function addFriendRequest(playerName, playerId, playId) {
		  var count = 0;
      if ($("#request_count").text().length > 0) {
        count = parseInt($("#request_count").text());
      }
      $("#request_count").text(++count);
      $("#request_count").show();
		  var clone = $("#notify-message").clone()
		  clone.attr("id", "req_" + playId);
      clone.html("<div><strong>" + playerName + "</strong> wants to be your friend</div>" +
          "<div style='display:inline'><a name='" + playId + "' rel='" + playerId +
          "' class='btn btn-success friend-accept' href='#'>Accept</a>&nbsp" +
          "<a name='" + playId + "' rel='" + playerId + "' class='friend-ignore btn btn-info' href='#'>Ignore</a>");
      clone.appendTo("#friend-request-view");
      clone.fadeIn(500);

      $(".friend-accept").click(function(){
    	  var toId = $(this).attr("rel");
        var metadata = ["from:{{ profile.id }}", "to:" + toId];
        $.post("/makePlay/", {"play_type":"create-relationship", "game_id":0, "metadata":metadata})
        .success(function(data){
        	var mex = "ACCEPT_FRIEND|{{ profile.name }}|" + toId + "|" + "{{ profile.id }}|";
          engineRef.sendMessage(mex, null, 5000);
        });
        var playId = $(this).attr("name");
        var count = 0;
        if ($("#request_count").text().length > 0) {
          count = parseInt($("#request_count").text() - 1);
        }
        cancelPlay(playId, count);
      });

      $(".friend-ignore").click(function(i, object){
    	  var playId = $(this).attr("name");
    	  var count = parseInt($("#request_count").text() - 1);
    	  cancelPlay(playId, count);
      });
	  }

	  {% for request in requests %}
	    addFriendRequest('{{ request.player_name }}', '{{ request.player_id }}', '{{ request.play_id }}');
	  {% endfor %}

	  $("#request_count").click(function(){
		  var count = parseInt($("#request_count").text());
		  if ($("#friend-request-view").is(":hidden")) {
			  $("#friend-request-view").slideDown(250);
		  }
		  else {
			  $("#friend-request-view").slideUp(250);
			  count -= $(".request-accept").length;
		    $("#request_count").text(count);
			  $(".request-accept").remove();
			  if (count < 1) {
          $("#request_count").fadeOut("slow");
        }
		  }
	  });

	  function cancelPlay(playId, count) {
		  $.post("/cancelPlay/", {"play_id": playId})
       .success(function(data) {
         $("#request_count").text(count);
         if (count == 0) {
           $("#request_count").fadeOut("slow");
           $("#friend-request-view").fadeOut("slow");
         }
         $("#req_" + playId).slideUp()
       });
	  }

		subscribeFeed(["game_player_connect_events_0_{{ profile.id }}"], ["placeholder"], null, onEngineReady);
		subscribeFeed(["player_{{ profile.id }}_friend_requests"], ["player_name", "player_id", "play_id"], onFriendRequestReceived, onEngineReady);
		subscribeFeed(["player_{{ profile.id }}_friend_accepts"], ["player_name", "player_id"], onAcceptRequestReceived, onEngineReady);
	});
</script>
